package com.lmiot.xyclick.Bean.SQL;

import android.content.Context;
import com.google.gson.Gson;
import com.lmiot.xyclick.Bean.SQL.DaoMaster;
import com.lmiot.xyclick.Bean.SQL.FGBeanDao;
import com.lmiot.xyclick.Util.FileUtils;
import java.util.ArrayList;
import java.util.List;
import org.greenrobot.greendao.query.WhereCondition;

public class FGBeanSqlUtil {
    private static final FGBeanSqlUtil ourInstance = new FGBeanSqlUtil();
    private FGBeanDao mFGBeanDao;

    public static FGBeanSqlUtil getInstance() {
        return ourInstance;
    }

    private FGBeanSqlUtil() {
    }

    public void initDbHelp(Context context) {
        this.mFGBeanDao = new DaoMaster(new DaoMaster.DevOpenHelper(context, "FGBean-db", null).getWritableDatabase()).newSession().getFGBeanDao();
    }

    public void add(FGBean fGBean) {
        this.mFGBeanDao.insertOrReplace(fGBean);
        saveLocal();
    }

    public void addList(List<FGBean> list) {
        this.mFGBeanDao.insertOrReplaceInTx(list);
    }

    public void update(FGBean fGBean) {
        this.mFGBeanDao.update(fGBean);
        saveLocal();
    }

    public void delByID(String str) {
        if (str == null) {
            str = "";
        }
        ArrayList arrayList = (ArrayList) this.mFGBeanDao.queryBuilder().where(FGBeanDao.Properties.FgID.eq(str), new WhereCondition[0]).list();
        if (arrayList.size() > 0) {
            this.mFGBeanDao.delete((FGBean) arrayList.get(0));
        }
        saveLocal();
    }

    public FGBean searchByName(String str) {
        ArrayList arrayList = (ArrayList) this.mFGBeanDao.queryBuilder().where(FGBeanDao.Properties.FgName.eq(str), new WhereCondition[0]).list();
        if (arrayList.size() > 0) {
            return (FGBean) arrayList.get(0);
        }
        return null;
    }

    public FGBean searchByID(String str) {
        if (str == null) {
            return null;
        }
        ArrayList arrayList = (ArrayList) this.mFGBeanDao.queryBuilder().where(FGBeanDao.Properties.FgID.eq(str), new WhereCondition[0]).list();
        if (arrayList.size() > 0) {
            return (FGBean) arrayList.get(0);
        }
        return null;
    }

    public List<FGBean> searchAll() {
        List<FGBean> list = this.mFGBeanDao.queryBuilder().orderAsc(FGBeanDao.Properties.Id).build().list();
        return list == null ? new ArrayList() : list;
    }

    private void saveLocal() {
        try {
            FileUtils.saveToLocalData("FG.fg", new Gson().toJson(getInstance().searchAll()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
